import 'package:creatures_world/net/cache_response.dart';
import 'package:creatures_world/net/file_cache_manager.dart';
import 'package:creatures_world/net/mm_cache_manager.dart';
import 'package:dio/dio.dart';

class CacheManager {


  static putCache(String url, Response response, {CachePolicy cachePolicy = CachePolicy.All}) {
    CacheResponse cacheResponse = CacheResponse.build(url, response, DateTime.now());
    if (cachePolicy == CachePolicy.All) {
      FileCacheManager.put(url, cacheResponse);
      MMCacheManager.put(url, cacheResponse);
    } else if (cachePolicy == CachePolicy.File) {
      FileCacheManager.put(url, cacheResponse);
    } else if (cachePolicy == CachePolicy.MM) {
      MMCacheManager.put(url, cacheResponse);
    }
  }

  static Future<Response?> getCache(String url, {CachePolicy cachePolicy = CachePolicy.All}) async {

    if (cachePolicy == CachePolicy.All) {
      if (existMMCache(url)) {
        return MMCacheManager.get(url)!.response;
      } else if (await existFileCache(url)) {
        return (await FileCacheManager.get(url))!.response;
      }
    } else if (cachePolicy == CachePolicy.File) {
      return (await FileCacheManager.get(url))!.response;
    } else if (cachePolicy == CachePolicy.MM) {
      return MMCacheManager.get(url)!.response;
    }

    return null;
  }

  static bool existMMCache(String url) {
    return MMCacheManager.exist(url);
  }

  static Future<bool> existFileCache(String url) async {
    return await FileCacheManager.exist(url);
  }
}

enum CachePolicy { All, File, MM }
